const {Sequelize, DataTypes, Op} = require('sequelize')
const path = require("path");
const basename = path.basename(__filename)
const fs = require("node:fs");
// const Op = Sequelize.Op
const config = {}
const db = {}
config.username = process.env.DB_USER
config.password = process.env.DB_PASSWORD
config.database = process.env.DB_NAME
config.host = process.env.DB_HOST
config.port = process.env.DB_PORT
config.dialect = process.env.DB_DIALECT
console.log(' process.env.SHOW_SQL', process.env.SHOW_SQL, typeof process.env.SHOW_SQL)
let sequelize = new Sequelize(config.database, config.username, config.password,
    Object.assign(config,
        {
            dialectOptions: {
                dateStrings: true,
                typeCast: true
            },
            pool: {
                max: 30,
                min: 0,
                acquire: 30000,
                idle: 10000
            },
            timezone: '+08:00',
            // 选择一种日志记录参数
            // logging: console.log,                  // 默认值,显示日志函数调用的第一个参数
            // logging: (...msg) => console.log(msg), // 显示所有日志函数调用参数
            logging: JSON.parse(process.env.SHOW_SQL) === true ? (...msg) => console.log(msg) : false,                        // 禁用日志记录
            // logging: msg => logger.debug(msg),     // 使用自定义记录器(例如Winston 或 Bunyan),显示第一个参数
            // logging: logger.debug.bind(logger)  ,   // 使用自定义记录器的另一种方法,显示所有消息
            define: { // 模型设置
                freezeTableName: true, // 自定义表面，不设置会自动将表名转为复数形式
                timestamps: false // 自动生成更新时间、创建时间字段：updatedAt,createdAt
            }
        })
)

let dir = path.join(__dirname)
let files = fs.readdirSync(dir)
let ff = files.filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
})
ff.forEach(file => {
    if (file !== 'init.js') {
        const model = require(path.join(dir, file))(sequelize, DataTypes)
        db[model.name] = model
    }
})

Object.keys(db).forEach(modelName => {
    if (db[modelName].associate) {
        db[modelName].associate(db)
    }
})


db.sequelize = sequelize
db.Sequelize = Sequelize
// module.exports = db;
module.exports = {
    sequelize,
    Sequelize,
    DataTypes,
    Op,
}
